//  全局参数

var layerIndexTip;  //  tips 关闭时 index
var socket;     // WebSocket 方法对象
var webSocket;  // WebSocket 地址
var host = "192.168.10.21"; // WebSocket IP 地址
var lockReconnect = false;  // 控制 WebSocket 重连
var userOperation = false;  // 判断用户是否在操作
var recognitionList = [];   // 存放操作时新患者


$(function () {
    //  初始化获取门店IP地址  启动 WebSocket
    obtainId()
});

//  获取线上 IP 地址
function obtainId() {
    //  门店 ID
    var params = {shopid: $("#deptIdValue").val()};
    $.ajax({
        type: "POST",
        url: Feng.ctxPath + "/integralMallWeixin/queryDeptIpByid",
        data: params,
        success: function (data) {
            var userId = $("#userIdValue").val(); // 登录ID
            host = data;
            webSocket = "ws://" + host + ":8089/websocket/" + userId + "";
            webSocketMethod();
        }
    });
}


//  -----------   WebSocket   -----------

// WebSocket方法集合
function webSocketMethod() {
    if (typeof WebSocket != 'undefined') {
        socket = new WebSocket(webSocket);
    } else {
        alert('Not support WebSocket！该浏览器不支持实时刷新，请使用谷歌浏览器急速模式！');
        return;
    }

    // WebSocket连接时触发
    socket.addEventListener('open', function (event) {
        webSocketOpen(event);
    });

    // WebSocket接收消息时触发
    socket.addEventListener('message', function (event) {
        webSocketMessage(event);
    });

    // WebSocket连接关闭时触发
    socket.addEventListener('close', function (event) {
        webSocketClose(event);
    });

    // WebSocket连接失败时触发
    socket.addEventListener('error', function (event) {
        webSocketError(event);
    });

}


function webSocketOpen(event) {
    console.log('连接成功');
}

function webSocketMessage(event) {
    //  数据处理
    var obj = eval('(' + event.data + ')');
    console.log(obj['data']);
    var image, membership;

    //  判断返回数据的类型
    switch (obj['type']) {
        case 'arrival':
            //  memberid = 0 为陌生人
            if (obj['data']['memberid'] == 0) {
                image = obj['data']['image'];
                membership = $("<li class='face-content-li unknownPeople'>" +
                    "<div><img class='face-content-img' src='data:image/png;base64," + image + "' alt='...'></div>" +
                    "<div>未知</div>" +
                    "<div>" + formatDate(obj['data']['time']) + "</div>" +
                    "<div class='dataTrack' value='" + obj['data']['id'] + "'></div>" +
                    "<div class='feature' value='" + obj['data']['feature'] + "'></div>" +
                    "<div class='quality' value='" + obj['data']['quality'] + "'></div>" +
                    "<div class='imageBs' value='" + obj['data']['image'] + "'></div>" +
                    "</li>");
            } else {
                image = obj['data']['image'];
                membership = $("<li class='face-content-li membership'>" +
                    "<div><img class='face-content-img' src='data:image/png;base64," + image + "' alt='...'></div>" +
                    "<div>" + obj['data']['member']['name'] + "</div>" +
                    "<div>" + formatDate(obj['data']['time']) + "</div>" +
                    "<div class='dataTrack' value='" + obj['data']['id'] + "'></div>" +
                    "<div class='feature' value='" + obj['data']['feature'] + "'></div>" +
                    "<div class='quality' value='" + obj['data']['quality'] + "'></div>" +
                    "<div class='imageBs' value='" + obj['data']['image'] + "'></div>" +
                    "<div class='name' value='" + obj['data']['member']['name'] + "'></div>" +
                    "<div class='phone' value='" + obj['data']['member']['phone'] + "'></div>" +
                    "<div class='sex' value='" + obj['data']['member']['sex'] + "'></div>" +
                    "<div class='age' value='" + obj['data']['member']['age'] + "'></div>" +
                    "<div class='mrnumber' value='" + obj['data']['member']['mrnumber'] + "'></div>" +
                    "<div class='memberid' value='" + obj['data']['memberid'] + "'></div>" +
                    "</li>");
            }

            //  判断用户是否操作 默认为false 用户操作时为true
            if (userOperation) {
                //  用户操作  向数组暂时添加数据
                recognitionList.push(obj);
                //  提示患者个数
                $("#face-btn-num").show().html(recognitionList.length);
            } else {
                //  判断长度  显示最新的五个
                if ($("#face-content-list li").length == 5) {
                    $("#face-content-list li").last().remove();
                    $("#face-content-list").prepend(membership);
                } else {
                    $("#face-content-list").prepend(membership);
                }
            }
            break;
    }
}

function webSocketClose(event) {
    console.log('连接关闭');
    reConnect();
}

function webSocketError(event) {
    console.log('连接失败');
}

// WebSocket 向服务器发送数据
function webSocketSend(obj) {
    socket.send(obj);
}

// WebSocket 重新向服务器发起连接请求
function reConnect() {
    if (lockReconnect) return;
    lockReconnect = true;
    //没连接上会一直重连，设置延迟避免请求过多
    setTimeout(function () {
        webSocketMethod();
        lockReconnect = false;
    }, 5000);
}

//  时间格式处理  返回用户到店时间 hh:mm
function formatDate(timestamp) {
    var time = new Date(parseInt(timestamp));
    var hours = time.getHours() < 10 ? "0" + time.getHours() : time.getHours();
    var minutes = time.getMinutes() < 10 ? "0" + time.getMinutes() : time.getMinutes();
    return hours + ":" + minutes;
}

//  WebSocket 向服务器告知注册
function webSocketRegister(id) {
    var obj = '{type:"featureByVisitor",data:{visitorid:' + id + '}}';
    webSocketSend(obj);
}

function register(obj) {
    var senddata = {};
    senddata.type = "addmember";
    var member = {};
    senddata.data = member;
    member.id = obj.id;
    member.memberid = obj.ids.split(",")[1];
    member.name = obj.memberName;
    member.avator = obj.avatar; //会员头像
    member.feature = obj.feature;
    member.quality = obj.quality;
    //add by member
    member.phone = obj.memberPhone;  //电话
    member.sex = obj.memberSex;  //性别
    member.age = obj.memberAge;  //年龄
    member.mrnumber = obj.medicalRecordNumber;  //病例号
    webSocketSend(JSON.stringify(senddata));
}


//  -----------   JQ 操作   -----------


//  侧边栏显示和隐藏
$("#faceRecognition").click(function () {
    $("#faceRecognition").hide();
    $("#faceRecognitionList").animate({marginRight: ""});
});
$("#face-retract").click(function () {
    $("#faceRecognition").show();
    $("#faceRecognitionList").animate({marginRight: "-100px"});
});

//  点击患者弹出  tips 层
$("#face-content-list").on('click', '.face-content-li', function (e) {
    e.stopPropagation();

    //  患者操作时为 true  禁止实时更新
    userOperation = true;

    //  给点击的患者添加 ID   控制 tips 层位置
    $(this).attr('id', 'tip-Selection').siblings().attr('id', '');


    var url = '',          //  背景图片
        information = '',  //  内容
        image = $(this).find('.face-content-img').attr('src'),  //  头像
        dataTrack = $(this).find('.dataTrack').attr('value'),   //  跟踪id
        feature = $(this).find('.feature').attr('value'),       //  特征码
        imageBs = $(this).find('.imageBs').attr('value'),       //  Bs64 图片格式
        quality = $(this).find('.quality').attr('value'),      //  特征码质量
        name = $(this).find('.name').attr('value'),         //  姓名
        phone = $(this).find('.phone').attr('value'),       //  电话
        sex = $(this).find('.sex').attr('value'),           //  性别
        age = $(this).find('.age').attr('value'),           //  年龄
        mrnumber = $(this).find('.mrnumber').attr('value'), //  病历号
        memberid = $(this).find('.memberid').attr('value');


    //  声明一个对象
    var parameter = {
        id: dataTrack,
        feature: feature,
        imageBs: imageBs,
        quality: quality
    };
    //  处理对象格式  传参
    var obj = JSON.stringify(parameter);

    //  判断当前用户是否会员  unknownPeople = 陌生人
    if ($(this).hasClass('unknownPeople')) {
        url =  'https://pynnn.oss-cn-hangzhou.aliyuncs.com/card01.png';
        information =
            "<div id='informationBox' style='background: url(" + url + ") no-repeat;background-size: 100% 100%;'>" +
            "<div class='information-top'>" +
            "<div class='information-img'><img class='face-content-img' src='" + image + "' alt='...'></div>" +
            "<div class='information-member'>陌生人</div>" +
            "</div>" +
            "<div class='information-btm'>" +
            "<div>" +
            "<input id='memberNum' type='text' placeholder='输入号码进行绑定'>" +
            "<button type='button' class='btn btn-default' id='memberBtn' onclick='bindingMember(" + obj + ")'>绑定</button>" +
            "</div>" +
            "</div>" +
            "</div>";
    } else {
        url =  'https://pynnn.oss-cn-hangzhou.aliyuncs.com/card02.png';
        sex = sex === '1' ? '男' : '女';
        information =
            "<div id='informationBox' style='background: url(" + url + ") no-repeat;background-size: 100% 100%;'>" +
            "<div class='information-top'>" +
            "<div class='information-img'><img class='face-content-img' src='" + image + "' alt='...'></div>" +
            "<div class='information-name' onclick='openMemberPage(" + '"'+ memberid +'"' + ")'><div>"+ name +"</div><div>"+ phone +"</div></div>" +
            "<div class='information-member'>会员</div>" +
            "</div>" +
            "<div class='information-btm'>" +
            "<div><span>"+ age +"岁</span>&nbsp;-&nbsp;<span>"+ sex +"</span>&nbsp;-&nbsp;<span>"+ mrnumber +"</span></div>" +
            "</div>" +
            "</div>";
    }

    //  弹出 tips 层
    layerIndexTip = layer.open({
        type: 4,
        tips: [2, '#ffffff'],
        closeBtn: 0,
        area: ['300px', '200px'],
        content: [information, '#tip-Selection']
    });
});

//  点击页面其他地方关闭 Tips层
$(document).click(function () {
    //  用户停止操作  启动实时刷新
    userOperation = false;
    $("#face-content-list").find('.face-content-li').attr('id', '');
    //  关闭 Tips层
    layer.close(layerIndexTip);
});

var strIframe = document.getElementById('childrenIframe');
strIframe.onload = function(){
    strIframe.contentDocument.onclick = function () {
        //  用户停止操作  启动实时刷新
        userOperation = false;
        $("#face-content-list").find('.face-content-li').attr('id', '');
        //  关闭 Tips层
        layer.close(layerIndexTip);
    }
};

//  阻止事件冒泡  点击 tips层  禁止关闭
$(document).on('click', '#informationBox', function (e) {
    e.stopPropagation();
});


//  点击全部  跳转页面
$("#face-btn-whole").click(function () {
    var index = layer.open({
        type: 2,
        title: '人脸识别全部患者',
        area: ['100%', '100%'],
        fix: true,
        maxmin: true,
        content: Feng.ctxPath + '/consultant/faceRecognition_whole'
    });
    this.layerIndex = index
});

//  刷新功能
function startUp() {
    //  启动实时更新
    userOperation = false;

    //  循环用户操作时 暂时存放的数据
    var unknownPeople;
    for (var i = 0; i < recognitionList.length; i++) {
        if (recognitionList[i]['data']['memberid'] == 0) {
            unknownPeople = $("<li class='face-content-li unknownPeople'>" +
                "<div><img class='face-content-img' src='data:image/png;base64," + recognitionList[i]['data']['image'] + "' alt='...'></div>" +
                "<div>未知</div>" +
                "<div>" + formatDate(recognitionList[i]['data']['time']) + "</div>" +
                "<div class='dataTrack' value='" + recognitionList[i]['data']['id'] + "'></div>" +
                "<div class='feature' value='" + recognitionList[i]['data']['feature'] + "'></div>" +
                "<div class='quality' value='" + recognitionList[i]['data']['quality'] + "'></div>" +
                "<div class='imageBs' value='" + recognitionList[i]['data']['image'] + "'></div>" +
                "</li>");
        } else {
            unknownPeople = $("<li class='face-content-li membership'>" +
                "<div><img class='face-content-img' src='data:image/png;base64," + recognitionList[i]['data']['image'] + "' alt='...'></div>" +
                "<div>" + recognitionList[i]['data']['name'] + "</div>" +
                "<div>" + formatDate(recognitionList[i]['data']['time']) + "</div>" +
                "<div class='dataTrack' value='" + recognitionList[i]['data']['id'] + "'></div>" +
                "<div class='feature' value='" + recognitionList[i]['data']['feature'] + "'></div>" +
                "<div class='quality' value='" + recognitionList[i]['data']['quality'] + "'></div>" +
                "<div class='imageBs' value='" + recognitionList[i]['data']['image'] + "'></div>" +
                "<div class='name' value='" + recognitionList[i]['data']['member']['name'] + "'></div>" +
                "<div class='phone' value='" + recognitionList[i]['data']['member']['phone'] + "'></div>" +
                "<div class='sex' value='" + recognitionList[i]['data']['member']['sex'] + "'></div>" +
                "<div class='age' value='" + recognitionList[i]['data']['member']['age'] + "'></div>" +
                "<div class='mrnumber' value='" + recognitionList[i]['data']['member']['mrnumber'] + "'></div>" +
                "<div class='memberid' value='" + recognitionList[i]['data']['memberid'] + "'></div>" +
                "</li>");
        }
        //  判断长度  显示最新的五个
        if ($("#face-content-list li").length == 5) {
            $("#face-content-list li").last().remove();
            $("#face-content-list").prepend(unknownPeople);
        } else {
            $("#face-content-list").prepend(unknownPeople);
        }
    }
    //  隐藏数字提示
    $("#face-btn-num").hide();
    //  清空存放数据数组
    recognitionList = [];
}

//  绑定会员注册
function bindingMember(obj) {
    //  向 WebSocket 服务器发送信息
    webSocketRegister(obj.id);
    // 向后台进行匹配
    obj.memberNum = $("#memberNum").val();
    var objs = JSON.stringify(obj);
    $.ajax({
        url: Feng.ctxPath + "/customer/membersBinding",
        type: "POST",
        dataType: "json",
        contentType: "application/json",
        data: objs,
        success: function (data) {
            var index = layer.open({
                type: 2,
                title: '预约客户电话匹配',
                area: ['45%', '60%'],
                fix: true,
                maxmin: true,
                content: Feng.ctxPath + '/customer/to_binding/' + data
            });
            this.layerIndex = index;
        }
    });
    //  关闭 Tips 层
    layer.close(layerIndexTip);
}

// 点击会员姓名进入详情
function openMemberPage(ide){
    $.ajax({
        url: Feng.ctxPath + "/consultantTwo/getdcsByCustomerId",
        type: "post",
        data: {
            "id": ide
        },
        success: function (data) {
            if (data == 1) {
                var index = layer.open({
                    type: 2,
                    title: '到店客户详情',
                    area: ['100%', '100%'],
                    fix: true,
                    maxmin: true,
                    content: Feng.ctxPath + '/customerDetails/to_openBileLists/' + ide + "/0"
                });
                this.layerIndex = index
            } else {
                alert("请先联系前台客服匹配建档！");
                return
            }
        }
    })
}